#include <stdio.h>
#include <unistd.h>
#include <sys/wait.h>
#include <string.h>
#include <stdlib.h>
#include <time.h>
int main(void)
{
	pid_t pid;
	int fd[2], i, n,n2;
	char buf[1024];
    char buf2[1024];

	int ret = pipe(fd);
	if(ret == -1){
		perror("pipe error");
		exit(1);
	}

	for(i = 0; i < 2; i++){
		if((pid = fork()) == 0)
			break;
		else if(pid == -1){
			perror("pipe error");
			exit(1);
		}
	}

	if (i == 0) {			
		//close(fd[1]);	
        for(int j=0;j<100;j++)
        {	
			sleep(1);
			srand((unsigned)time(NULL));
            n = read(fd[0], buf, 1024);     //从管道中读数据
			printf("[1]:(%d):%s",n,buf);
            // write(STDOUT_FILENO, "[2]: ", sizeof("[2]: "));
            // write(STDOUT_FILENO, buf, n);
            sleep(rand()%3);	
        }		
	} else if(i == 1) {	
		//close(fd[1]);	
        for(int j=0;j<100;j++)
        {			
			srand((unsigned)time(NULL));
            n2 = read(fd[0], buf2, 1024);     //从管道中读数据
			printf("[2]:(%d):%s",n2,buf2);
            // write(STDOUT_FILENO, "[1]: ", sizeof("[1]: "));
            // write(STDOUT_FILENO, buf2, n);
            sleep(rand()%3);
        }
	} else {
		//close(fd[0]);       //父进程关闭写端,留读端读取数据    
//		sleep(1);
		for(int j=0;j<100;j++)
        {
            write(fd[1], "hello\n", strlen("1.hello\n"));
            sleep(1);
        }
		for(i = 0; i < 2; i++)		//两个儿子wait两次
			wait(NULL);
	}

	return 0;
}
